import axios from "axios";
import { LogType, type ApiLogDataDto } from "./indexedDB.type";
import { uploadLogs } from "./cosUpload";
import { IndexedDBHelper } from "./indexedDB";

// 创建 Axios 实例
const axiosInstance = axios.create({
    baseURL: 'https://dev-1300222288.cos.ap-shanghai.myqcloud.com', // 替换为你的 API URL
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        config.headers['Authorization'] = 'Bearer your_token';
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        const { response, message } = error;
        const dbHelper = new IndexedDBHelper<ApiLogDataDto>('logdb_api', 'store_api');

        //api报错本地存储日志
        dbHelper.addData({
            apiUrl: response.request.responseURL,
            method: response.config.method,
            params: response.config.data,
            status: response.status,
            statusText: response.statusText,
            message: message,
            response: JSON.stringify(response),
            pageUrl: window.location.href,
            logType: LogType.ERROR
        }).then(() => {
            //api报错上报日志
            // dbHelper.getAllData().then((res: any[]) => {
            //     uploadLogs(JSON.stringify(res), `${dbHelper.dbName}_${dbHelper.storeName}`, (path: string) => {
            //         console.log("日志上传成功，路径：" + path);
            //     });
            // });
        });

        return Promise.reject(error)
    }
);

export default axiosInstance;